package com.daisuxia.web.util.encrypt;

import java.math.BigDecimal;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;

import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.WebClient;
import com.daisuxia.mg.model.UserBlacklist;
import com.daisuxia.mg.model.UserGray;
import com.daisuxia.mg.model.UserGridInfo;
import com.daisuxia.mg.model.UserGridResponse;
import com.daisuxia.mg.model.UserSearchedHistoryByOrgs;
import com.daisuxia.risk.pojo.RiskCreditUser;
import com.daisuxia.risk.utils.ConstantRisk;
import com.daisuxia.risk.utils.jyzx.JsonSerializer;
import com.daisuxia.risk.utils.jyzx.LoanInfo;
import com.daisuxia.risk.utils.jyzx.Pkg2003;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;

public class AESUtil {
	public final static String KEY = "!@#$%^&*(";

	/**
	 * 
	 * @param content
	 * @param password
	 * @return
	 */
	public static String encrypt(String content, String password) {
		try {
			if (StringUtils.isBlank(password)) {
				password = KEY;
			}
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(password.getBytes());
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] result = cipher.doFinal(byteContent);
			return ByteUtil.byteArr2HexStr(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String decrypt(String content, String password) {
		try {
			if (StringUtils.isBlank(password)) {
				password = KEY;
			}
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");// 修复linux系统报错问题
			secureRandom.setSeed(password.getBytes());
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] result = cipher.doFinal(ByteUtil.hexStr2ByteArr(content));
			return new String(result, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 查openId
	 */
	public static void getOpenId() {
		try {
			String name = "范银川";
			String cardNum = "411324199009044030";
			String userId = "7";
			String value = "userName=" + name + "&cardNum=" + cardNum + "&userId=" + userId;
			System.out.println(value);
			String result = WebClient.getInstance().doPost("http://180.173.0.188:8999/back/risk/test?" + value, null);
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 查openId
	 */
	public static void getURL() {
		try {
			String name = "范银川";
			String cardNum = "411324199009044030";
			String userId = "7";
			String value = "userName=" + name + "&cardNum=" + cardNum + "&userId=" + userId;
			System.out.println(value);
			String result = WebClient.getInstance().doPost("http://180.173.0.188:8999/back/risk/test?" + value, null);
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 查openId
	 */
	public static void getScore() {
		try {
			String openId = "268816231939676957957903450";
			String userId = "7";
			String value = "userId=" + userId + "&openId=" + openId;
			System.out.println(value);
			String result = WebClient.getInstance().doPost("http://180.173.0.188:8999/back/risk/test?" + value, null);
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 生成同盾贷前报告
	 */
	public static void getTd() {
		try {
			// 893939741@qq.com
			String userId = "7";
			String userName = "皮晴晴";
			String userPhone = "13333333333";
			String cardNum = "370404199006301915";
			// String userId = "7";
			// String userName = "陈凯炜";
			// String userPhone = "13918201587";
			// String cardNum = "330381198511281455";
			String value = "userId=" + userId + "&userName=" + userName + "&userPhone=" + userPhone + "&cardNum=" + cardNum;
			System.out.println(value);
			String result = WebClient.getInstance().doPost("http://180.173.0.188:8999/back/risk/test?" + value, null);
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 获得同盾贷前报告
	 */
	public static void getTdReport() {
		try {
			String userId = "7";
			String reportId = "ER2016121312594913325789";
			String value = "userId=" + userId + "&reportId=" + reportId;
			System.out.println(value);
			String result = WebClient.getInstance().doPost("http://180.173.0.188:8999/back/risk/test?" + value, null);
			ServiceResult serviceResult = JSONUtil.jsonToBean(result, ServiceResult.class);
			JSONObject jsonObject = JSONObject.fromObject(serviceResult.getMsg());
			if (jsonObject.getBoolean("success")) {
				BigDecimal tdScore = new BigDecimal(jsonObject.getString("final_score"));
				JSONArray jsonArray = jsonObject.getJSONArray("risk_items");
				Integer tdPhoneBlack = 0;
				Integer tdCardNumBlack = 0;
				Integer tdMonth1Borrow = 0;
				Integer tdDay7Borrow = 0;
				Integer tdMonth3CardApply = 0;
				Integer tdMonth3ApplyCard = 0;
				Integer tdMonth1CardNumDeviceBorrow = 0;
				Integer tdDay7DeviceCardOrPhoneBorrow = 0;
				Integer tdDay7CardDevice = 0;
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject jsonObject2 = jsonArray.getJSONObject(i);
					String itemName = jsonObject2.getString("item_name");
					JSONObject jsonObject3 = jsonObject2.getJSONObject("item_detail");
					if (ConstantRisk.TD_PHONE_BLACK.equals(itemName)) {
						tdPhoneBlack = jsonObject3.getJSONArray("namelist_hit_details").size();
					} else if (ConstantRisk.TD_CARD_BLACK.equals(itemName)) {
						tdCardNumBlack = jsonObject3.getJSONArray("namelist_hit_details").size();
					} else if (ConstantRisk.TD_MONTH1_BLACK.equals(itemName)) {
						tdMonth1Borrow = jsonObject3.getInt("platform_count");
					} else if (ConstantRisk.TD_DAY7_BLACK.equals(itemName)) {
						tdDay7Borrow = jsonObject3.getInt("platform_count");
					} else {
						if (jsonObject3.containsKey("frequency_detail_list")) {
							JSONArray jsonArray2 = jsonObject3.getJSONArray("frequency_detail_list");
							if (jsonArray2 != null && jsonArray2.size() > 0) {
								for (int j = 0; j < jsonArray2.size(); j++) {
									JSONObject jsonObject4 = jsonArray2.getJSONObject(j);
									String detail = jsonObject4.getString("detail");
									int index = detail.indexOf("：") + 1;
									if (index >= 0) {
										int num = Integer.valueOf(detail.substring(index));
										if (ConstantRisk.TD_MONTH3_CARD_APPLY.equals(itemName)) {
											tdMonth3CardApply += num;
										} else if (ConstantRisk.TD_MONTH3_APPLY_CARD.equals(itemName)) {
											tdMonth3ApplyCard += num;
										} else if (ConstantRisk.TD_MONTH1_CARD_NUM_DEVICE_BORROW.equals(itemName)) {
											tdMonth1CardNumDeviceBorrow += num;
										} else if (ConstantRisk.TD_DAY7_DEVICE_CARD_OR_PHONE_BORROW.equals(itemName)) {
											tdDay7DeviceCardOrPhoneBorrow += num;
										} else if (ConstantRisk.TD_DAY7_CARD_DEVICE.equals(itemName)) {
											tdDay7CardDevice += num;
										}
									}
								}
							}
						}
					}
				}
				RiskCreditUser riskCreditUser = new RiskCreditUser(Integer.valueOf(userId), tdScore, tdPhoneBlack, tdCardNumBlack, tdMonth1Borrow,
						tdDay7Borrow, tdMonth1CardNumDeviceBorrow, tdDay7DeviceCardOrPhoneBorrow, tdDay7CardDevice, tdMonth3ApplyCard,
						tdMonth3CardApply, null);
			}

			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 白骑士白名单
	 */
	public static void getBqs() {
		try {
			String userId = "7";
			String userName = "陈凯炜";
			String userPhone = "13918201587";
			String cardNum = "330381198511281455";
			// String userName = "范银川";
			// String userPhone = "18917583863";
			// String cardNum = "411324199009044030";
			String value = "userId=" + userId + "&userName=" + userName + "&userPhone=" + userPhone + "&cardNum=" + cardNum;
			System.out.println(value);
			String result = WebClient.getInstance().doPost("http://180.173.0.188:8999/back/risk/test?" + value, null);
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 91征信
	 */
	public static void getJy() {
		try {
			String userId = "7";
			String userName = "陈水金";
			String cardNum = "350424198301082038";
			String value = "userId=" + userId + "&userName=" + userName + "&cardNum=" + cardNum;
			System.out.println(value);
			String result = WebClient.getInstance().doPost("http://180.173.0.188:8999/back/risk/test?" + value, null);
			ServiceResult serviceResult = JSONUtil.jsonToBean(result, ServiceResult.class);
			Pkg2003 pkg2003 = (Pkg2003) JsonSerializer.deserializer(serviceResult.getMsg(), new TypeReference<Pkg2003>() {
			});
			int jyLoanNum = 0;
			int jyJdNum = 0;
			BigDecimal jyJdBl = BigDecimal.ZERO;
			int jyOverNum = 0;
			BigDecimal jyOverBl = BigDecimal.ZERO;
			List<LoanInfo> list = pkg2003.getLoanInfos();
			if (list != null && list.size() > 0) {
				jyLoanNum = list.size();
				for (LoanInfo loanInfo : list) {
					if (loanInfo.getBorrowState() == 1) {
						jyJdNum++;
					}
					short status = loanInfo.getRepayState();
					if ((status != 0 && status != 1 && status != 9) || loanInfo.getArrearsAmount() > 0) {
						jyOverNum++;
					}
				}
				jyJdBl = new BigDecimal(jyJdNum).divide(new BigDecimal(jyLoanNum), 2, BigDecimal.ROUND_UP);
				jyOverBl = new BigDecimal(jyOverNum).divide(new BigDecimal(jyLoanNum), 2, BigDecimal.ROUND_UP);
			}
			// RiskCreditUser riskCreditUser = new RiskCreditUser(Integer
			// .valueOf(userId), jyLoanNum, jyJdNum, jyJdBl, jyOverNum,
			// jyOverBl);
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 聚信立密罐
	 */
	public static void getMg() {
		try {
			String userId = "130438";
			String userName = "范银川";
			String userPhone = "15139002006";
			String cardNum = "411324199009044030";
			// String userName = "陈凯炜";
			// String userPhone = "13918201587";
			// String cardNum = "330381198511281455";
			String value = "userId=" + userId + "&userName=" + userName + "&userPhone=" + userPhone + "&cardNum=" + cardNum;
			String result = WebClient.getInstance().doPost("http://localhost/back/risk/test?" + value, null);
			System.out.println(result);
			ServiceResult serviceResult = JSONUtil.jsonToBean(result, ServiceResult.class);
			Map<String, Class> classMap = new HashMap<String, Class>();
			classMap.put("user_searched_history_by_orgs", UserSearchedHistoryByOrgs.class);
			classMap.put("user_gray", UserGray.class);

			UserGridResponse userGridResponse = (UserGridResponse) JSONObject.toBean(JSONObject.fromObject(serviceResult.getMsg()),
					UserGridResponse.class, classMap);
			UserGridInfo userGridInfo = userGridResponse.getData();
			UserBlacklist userBlacklist = userGridInfo.getUser_blacklist();
			Integer mgBlack = 2;
			if (userBlacklist.isBlacklist_name_with_idcard() || userBlacklist.isBlacklist_name_with_phone()) {
				mgBlack = 1;
			}
			Integer mgDay7Num = 0;
			Integer mgMonth1Num = 0;
			List<UserSearchedHistoryByOrgs> list = userGridInfo.getUser_searched_history_by_orgs();
			if (list != null && list.size() > 0) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date now = DateUtil.getDate(sdf.format(new Date()), "yyyy-MM-dd");
				for (UserSearchedHistoryByOrgs userSearchedHistoryByOrgs : list) {
					Date date = DateUtil.getDate(userSearchedHistoryByOrgs.getSearched_date(), "yyyy-MM-dd");
					int between = DateUtil.daysBetween(date, now);
					if (between <= 30) {
						mgMonth1Num++;
						if (between <= 7) {
							mgDay7Num++;
						}
					}

				}
			}
			UserGray userGray = userGridInfo.getUser_gray();
			RiskCreditUser riskCreditUser = new RiskCreditUser(Integer.valueOf(userId), new BigDecimal(userGray.getPhone_gray_score()), mgDay7Num,
					mgMonth1Num, mgBlack);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 聚信立token和获得验证码
	 */
	public static void getJxl() {
		try {
			HashMap<String, String> params = new HashMap<String, String>();
			params.put("userName", "赵一航");
			params.put("cardNum", "411324199004242230");
			params.put("mobile", "15011309065");
			params.put("userId", "7");
			String result = WebClient.getInstance().doPost("http://180.173.0.188:8999/back/risk/test", params);
			System.out.println(result);
			ServiceResult serviceResult = JSONUtil.jsonToBean(result, ServiceResult.class);
			String msg = serviceResult.getMsg();
			if (serviceResult.isSuccessed()) {
				params.put("website", serviceResult.getExt().toString());
				params.put("password", "zhao1hang");
				params.put("queryPwd", "592585");
				params.put("token", msg);
				result = WebClient.getInstance().doPost("http://180.173.0.188:8999/back/risk/test1", params);
				System.out.println(result);
			} else {
				System.out.println(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 聚信立提交报告申请
	 */
	public static void getJxl2() {
		try {
			HashMap<String, String> params = new HashMap<String, String>();
			params.put("userName", "赵一航");
			params.put("cardNum", "411324199004242230");
			params.put("mobile", "15011309065");
			params.put("userId", "7");
			String result = WebClient.getInstance().doPost("http://180.173.0.188:8999/back/risk/test", params);
			System.out.println(result);
			ServiceResult serviceResult = JSONUtil.jsonToBean(result, ServiceResult.class);
			String msg = serviceResult.getMsg();
			if (serviceResult.isSuccessed()) {
				params.put("website", serviceResult.getExt().toString());
				params.put("password", "zhao1hang");
				params.put("queryPwd", "592585");
				params.put("token", msg);
				result = WebClient.getInstance().doPost("http://180.173.0.188:8999/back/risk/test1", params);
				System.out.println(result);
			} else {
				System.out.println(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 *宜信信息
	 */
	public static void getYx() {
		try {
			String userId = "7";
			// 有数据无风险
			// String userName = "董计亮";
			// String cardNum = "320325197111075014";
			// 无数据
			// String userName = "范银川";
			// String userPhone = "18917583863";
			// String cardNum = "411324199009044030";
			// 有风险
			String userName = "刘兵";
			String cardNum = "370633197005042513";
			String value = "userId=" + userId + "&userName=" + userName + "&cardNum=" + cardNum;
			System.out.println(value);
			String result = WebClient.getInstance().doPost("http://180.173.0.188:8999/back/risk/test?" + value, null);
			System.out.println(result);
			ServiceResult serviceResult = JSONUtil.jsonToBean(result, ServiceResult.class);
			String msg = serviceResult.getMsg();
			if (serviceResult.isSuccessed()) {
				Integer yxFxNum = 0;
				Integer yxMonth3Over = 0;
				Integer yxLessMonth3Over = 0;
				Integer total = 0;
				JSONObject jsonObject = JSONObject.fromObject(msg);
				JSONObject jsonObject2 = jsonObject.getJSONObject("data");
				if (jsonObject2.containsKey("riskResults")) {
					JSONArray jsonArray = jsonObject2.getJSONArray("riskResults");
					if (jsonArray != null && jsonArray.size() > 0) {
						yxFxNum = jsonArray.size();
					}
				}
				if (jsonObject2.containsKey("loanRecords")) {
					JSONArray jsonArray = jsonObject2.getJSONArray("loanRecords");
					if (jsonArray != null && jsonArray.size() > 0) {
						total = jsonArray.size();
						for (int i = 0; i < jsonArray.size(); i++) {
							JSONObject jsonObject3 = jsonArray.getJSONObject(i);
							String tmpTotal = jsonObject3.getString("overdueTotal");
							if (StringUtils.isNotBlank(tmpTotal)) {
								total += Integer.valueOf(tmpTotal);
								String tmpM3 = jsonObject3.getString("overdueM3");
								if (StringUtils.isNotBlank(tmpM3)) {
									yxMonth3Over += Integer.valueOf(tmpM3);
								}

							}
						}
					}
				}
				yxLessMonth3Over = total - yxMonth3Over;
			} else if ("100".equals(serviceResult.getCode())) {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 聚信立提交报告申请
	 */
	public static void getZzc() {
		try {
			// String userName = "吴双奇";
			// String cardNum = "352229198411130515";
			// String userPhone = "13505949572";
			String userName = "范银川";
			String cardNum = "411324199009044030";
			String userPhone = "18917583863";

			HashMap<String, String> params = new HashMap<String, String>();
			params.put("userName", userName);
			params.put("cardNum", cardNum);
			params.put("userPhone", userPhone);
			params.put("userId", "7");
			String result = WebClient.getInstance().doPost("http://localhost/back/risk/test", params);
			System.out.println(result);
			ServiceResult serviceResult = JSONUtil.jsonToBean(result, ServiceResult.class);
			String msg = serviceResult.getMsg();
			if (serviceResult.isSuccessed()) {
				JSONObject jsonObject = JSONObject.fromObject(msg);
				System.out.println(jsonObject.getInt("count"));
			} else {
				System.out.println(msg);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 中智诚反欺诈
	 */
	public static void getZzcFqz() {
		try {
			// String userName = "吴双奇";
			// String cardNum = "352229198411130515";
			// String userPhone = "13505949572";
			String userName = "范银川";
			String cardNum = "411324199009044030";
			String userPhone = "18917583863";

			HashMap<String, String> params = new HashMap<String, String>();
			params.put("userName", userName);
			params.put("cardNum", cardNum);
			params.put("userPhone", userPhone);
			params.put("userId", "130438");
			String result = WebClient.getInstance().doPost("http://localhost/back/risk/test", params);
			System.out.println(result);
			ServiceResult serviceResult = JSONUtil.jsonToBean(result, ServiceResult.class);
			String msg = serviceResult.getMsg();
			if (serviceResult.isSuccessed()) {
				JSONObject jsonObject = JSONObject.fromObject(msg);
				System.out.println(jsonObject.getInt("count"));
			} else {
				System.out.println(msg);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 中智诚反欺诈
	 */
	public static void getZzcFqzQuery() {
		try {
			// String userName = "吴双奇";
			// String cardNum = "352229198411130515";
			// String userPhone = "13505949572";
			String zzcId = "AP201701152451530942";

			HashMap<String, String> params = new HashMap<String, String>();
			params.put("zzcId", zzcId);
			params.put("userId", "2623");
			String result = WebClient.getInstance().doPost("http://localhost/back/risk/test", params);
			System.out.println(result);
			ServiceResult serviceResult = JSONUtil.jsonToBean(result, ServiceResult.class);
			String msg = serviceResult.getMsg();
			if (serviceResult.isSuccessed()) {
				JSONObject jsonObject = JSONObject.fromObject(msg);
				System.out.println(jsonObject.getInt("count"));
			} else {
				System.out.println(msg);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	/**
	 * 算话反欺诈
	 */
	public static void getShFqzQuery() {
		try {
			HashMap<String, String> params = new HashMap<String, String>();
			params.put("userId", "2623");
			String result = WebClient.getInstance().doPost("http://localhost/back/risk/test", params);
			System.out.println(result);
			ServiceResult serviceResult = JSONUtil.jsonToBean(result, ServiceResult.class);
			String msg = serviceResult.getMsg();
			System.out.println(msg);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 算话反欺诈
	 */
	public static void updateSy() {
		try {
			HashMap<String, String> params = new HashMap<String, String>();
			params.put("userId", "3");
			params.put("orderNo", "91014844715915281");
			params.put("status", "21");
			String result = WebClient.getInstance().doPost("http://localhost/back/risk/test2", params);
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public static void main(String[] args) {
		// getOpenId();
		// getURL();
		// getScore();
		// getTd();
		// getTdReport();
		// getBqs();
		// getJy();
//		 getMg();
		// getJxl();
		// getYx();
//		 getZzcFqz();
//		getZzcFqzQuery();
//		getShFqzQuery();
		updateSy();
	}
}
